package com.yexs.controller;


import com.yexs.common.exception.UploadFileException;
import com.yexs.common.vo.Result;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/file")
public class FileUploadController {

    private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @Value("${baseFileUploadPath}")
    private String baseFileUploadPath;

    /**
     * singleFile.html页面
     */
    @GetMapping("singleFile")
    public String singleFile() {
        return "/singleFileUpload";
    }

    /**
     * multiFile.html页面
     */
    @GetMapping("multiFile")
    public String multiFile() {
        return "/multiFileUpload";
    }

    /**
     * BigMultiFile.html页面
     */
    @GetMapping("bigMultiFile")
    public String bigMultiFile() {
        return "/bigMultiFileUpload";
    }

    /**
     * BigMultiFile.html页面
     */
    @GetMapping("bigMultiFile2")
    public String bigMultiFile2() {
        return "/bigMultiFileUpload2";
    }

    private File getWillSavePath(MultipartFile file) {
        if (file.isEmpty()) {
            throw new UploadFileException(-1, "上传的文件为空(么有内容)");
        }
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        System.out.println(fileName + "-->" + size);

        File dest = new File(baseFileUploadPath + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        return dest;
    }

    /**
     * 大文件上传
     *
     * @param file
     * @return
     */
    @RequestMapping("/bigMultiFileUpload")
    @ResponseBody
    public Result bigMultiFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        file.transferTo(getWillSavePath(file)); //保存文件
        return Result.SUCCESS("上传文件成功");
    }

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @RequestMapping("/singleFileUpload")
    @ResponseBody
    public Result singleFileUpload(@RequestParam("fileName") MultipartFile file) throws IOException {
        file.transferTo(getWillSavePath(file)); //保存文件
        return Result.SUCCESS("上传文件成功");
    }


    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "multiFileUpload")
    @ResponseBody
    public Result multiFileUpload(HttpServletRequest request) throws IOException {
        //public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files)

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");

        if (files.isEmpty()) {
            return Result.ERROR(-1, "上传文件失败");
        }
        for (MultipartFile file : files) {
            file.transferTo(getWillSavePath(file));
        }
        return Result.SUCCESS("批量上传文件成功");
    }

    /**
     * 文件上传失败的重定向 url
     *
     * @param request
     * @return
     */
    @RequestMapping("uploadStatus")
    @ResponseBody
    public Result uploadStatus(HttpServletRequest request) {
        //RequestContextUtils.getInputFlashMap(request)来获取addFlashAttribute的值
        Map<String, ?> map = RequestContextUtils.getInputFlashMap(request);
        String message = (String) map.get("message");
        return Result.ERROR(-1, message != null ? message : "error Exception");
    }

    /**
     * 文件下载
     *
     * @param response
     * @return
     */
    @RequestMapping("download")
    public void downLoad(HttpServletResponse response, String fileName) throws IOException {
        try {
            if (fileName == null || fileName.length() < 1) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print("请输入必填的fileName参数");
                return;
            }
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            FileUtils.copyFile(new File(baseFileUploadPath + "/" + fileName), outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            logger.error("处理失败", e);
        }
        return;
    }
}
